<template>
	<div class="wrapper">

		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">确认订单</h1>
				</section>
			</div>
		</header>

		<!-- 订单信息部分 -->
		<div class="order-info-card">
			<div class="card-header">
				<i class="material-icons">location_on</i>
				<h5>订单配送至</h5>
			</div>
			<div class="order-info-address" @click="toUserAddress">
				<p class="address-text">{{deliveryaddress!=null?deliveryaddress.address:'请选择送货地址'}}</p>
				<i class="material-icons">chevron_right</i>
			</div>
			<div class="user-info">
				<i class="material-icons">person</i>
				<span>{{user.userName}}{{sexFilter}} <span v-if="user.role === 1">{{user.userId}}</span></span>
			</div>
		</div>

		<!-- 商家信息 -->
		<div class="business-card">
			<i class="material-icons business-icon">store</i>
			<h3>{{business.businessName}}</h3>
		</div>

		<!-- 订单明细部分 -->
		<div class="order-items-card">
			<div class="card-header">
				<i class="material-icons">shopping_cart</i>
				<h5>订单明细</h5>
			</div>
			<div class="order-items-list">
				<div v-for="item in filteredCartArr" :key="item.foodId" class="order-item">
					<div class="item-left">
						<img :src="getImg(item.foodImg)" @error="handleImageError" class="item-img">
						<div class="item-info">
							<p class="item-name">{{item.foodName}}</p>
							<p class="item-quantity">x {{item.quantity}}</p>
						</div>
					</div>
					<p class="item-price">¥{{roundToDecimalPlace(item.foodPrice*item.quantity,2)}}</p>
				</div>
				<div class="order-item delivery-fee-item">
					<div class="item-left">
						<i class="material-icons delivery-icon">local_shipping</i>
						<p class="item-name">配送费</p>
					</div>
					<p class="item-price">¥{{business.deliveryPrice}}</p>
				</div>
			</div>
		</div>

		<!-- 优惠券部分 -->
		<div class="coupon-card">
			<div class="card-header">
				<i class="material-icons">card_giftcard</i>
				<h5>使用优惠券</h5>
			</div>
			<div class="coupon-selector">
				<div v-if="availableCoupons.length > 0" class="coupon-list">
					<!-- 不使用优惠券选项 -->
					<div 
						class="coupon-item" 
						:class="{ selected: selectedCouponId === '' }"
						@click="selectedCouponId = ''"
					>
						<div class="coupon-item-left">
							<i class="material-icons">close</i>
							<span>不使用优惠券</span>
						</div>
						<i class="material-icons check-icon">check_circle</i>
					</div>
					<!-- 优惠券列表 -->
					<div 
						v-for="coupon in availableCoupons" 
						:key="coupon.couponId"
						class="coupon-item"
						:class="{ selected: selectedCouponId == coupon.couponId }"
						@click="selectedCouponId = coupon.couponId"
					>
						<div class="coupon-item-left">
							<div class="coupon-amount">
								<span class="currency">¥</span>
								<span class="amount">{{ coupon.discountAmount }}</span>
							</div>
							<div class="coupon-info">
								<p class="coupon-name">{{ coupon.couponName }}</p>
								<p class="coupon-condition" v-if="coupon.minimumAmount > 0">
									满¥{{ coupon.minimumAmount }}可用
								</p>
								<p class="coupon-condition" v-else>
									无门槛使用
								</p>
							</div>
						</div>
						<i class="material-icons check-icon">check_circle</i>
					</div>
				</div>
				<div v-else class="no-coupon-tip">
					<i class="material-icons">info</i>
					<span>暂无可用优惠券</span>
					<router-link to="/pointsstore" class="link-to-store">去积分商店兑换</router-link>
				</div>
			</div>
		</div>

		<!-- 合计部分 -->
		<div class="total-bar">
			<div class="total-info">
				<div class="price-row">
					<span class="price-label">商品合计：</span>
					<span class="price-amount">¥{{roundToDecimalPlace(subtotal,2)}}</span>
				</div>
				<div class="price-row" v-if="selectedCoupon">
					<span class="price-label discount">
						<i class="material-icons discount-icon">card_giftcard</i>
						优惠券减免：
					</span>
					<span class="price-amount discount">-¥{{roundToDecimalPlace(selectedCoupon.discountAmount,2)}}</span>
				</div>
				<div class="price-row" v-if="userLevel < 5">
					<span class="price-label discount">
						<i class="material-icons discount-icon">military_tech</i>
						Lv{{userLevel}}折扣：
					</span>
					<span class="price-amount discount">-¥{{roundToDecimalPlace(levelDiscountAmount,2)}}</span>
				</div>
				<div class="price-row total">
					<span class="total-label">实付金额：</span>
					<span class="total-amount">¥{{roundToDecimalPlace(finalPrice,2)}}</span>
				</div>
				<div class="savings-tip" v-if="selectedCoupon || userLevel < 5">
					<i class="material-icons">celebration</i>
					<span>已为您节省 ¥{{roundToDecimalPlace(totalSavings,2)}}</span>
				</div>
			</div>
			<button class="pay-button" @click="toPayment">
				<i class="material-icons">payment</i>
				<span>去支付</span>
			</button>
		</div>
	</div>
</template>

<script>
	import BackButton from '../components/BackButton.vue';
	export default{
		name:'UserOrders',
		data(){
			return {
				businessId:this.$route.query.businessId,
				business:{},
				user:{},
				cartArr:[],
				deliveryaddress:{},
				availableCoupons: [],
				selectedCouponId: '',
				userLevel: 1,
				userDiscount: 99
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');
			console.log(this.user);
			
			// 加载用户等级和折扣信息
			this.loadUserLevelInfo();
			
			// 从 localStorage 读取用户选择的地址
			const selectedAddress = this.$getLocalStorage('selectedAddress_' + this.user.userId);
			if (selectedAddress) {
				this.deliveryaddress = selectedAddress;
			}
			console.log('已选择地址：', this.deliveryaddress);
			
			//查询当前商家
			this.$axios.post('BusinessController/getBusinessById',this.$qs.stringify({
				businessId:this.businessId
			})).then(response=>{
				this.business = response.data;
			}).catch(error=>{
				console.error(error);
			});
			
			// 查询当前用户在购物车中的当前商家食品列表
			// 某些入口可能没有传递 foodArr，避免直接 JSON.parse(undefined) 报错
			const foodArrParam = this.$route.query.foodArr;
			if (foodArrParam) {
				try {
					this.cartArr = JSON.parse(foodArrParam);
				} catch (e) {
					console.error('解析 foodArr 出错：', e, '原始值为：', foodArrParam);
					this.cartArr = [];
				}
			} else {
				console.warn('路由中未找到 foodArr 参数，使用空购物车');
				this.cartArr = [];
			}
			
			// 加载用户可用优惠券
			this.loadAvailableCoupons();
		},
		computed:{
			subtotal(){
				let subtotal = 0;
				for(let cartItem of this.cartArr){
					subtotal += cartItem.foodPrice*cartItem.quantity;
				}
				subtotal += this.business.deliveryPrice || 0;
				return subtotal;
			},
			totalPrice(){
				return this.subtotal;
			},
			selectedCoupon(){
				if (!this.selectedCouponId) return null;
				return this.availableCoupons.find(c => c.couponId == this.selectedCouponId);
			},
			levelDiscountAmount(){
				// 等级折扣金额 = 优惠券折扣后的价格 * (100 - 折扣) / 100
				let priceAfterCoupon = this.subtotal;
				if (this.selectedCoupon) {
					priceAfterCoupon = Math.max(0, priceAfterCoupon - this.selectedCoupon.discountAmount);
				}
				
				if (this.userDiscount < 100) {
					return priceAfterCoupon * (100 - this.userDiscount) / 100.0;
				}
				return 0;
			},
			finalPrice(){
				let price = this.subtotal;
				// 先应用优惠券折扣
				if (this.selectedCoupon) {
					price = Math.max(0, price - this.selectedCoupon.discountAmount);
				}
				// 再应用等级折扣
				if (this.userDiscount < 100) {
					price = Math.max(0, price - this.levelDiscountAmount);
				}
				return price;
			},
			totalSavings(){
				let savings = 0;
				if (this.selectedCoupon) {
					savings += this.selectedCoupon.discountAmount;
				}
				savings += this.levelDiscountAmount;
				return savings;
			},
			sexFilter(){
				if(this.user.userSex==1)return '先生';
				else if(this.user.userSex==0)return '女士';
				else return '';
			},
			filteredCartArr() {
				return this.cartArr.filter(item => item.quantity > 0);
			}
		},
		methods:{
			getImg(path){
			if(!path) return this.getDefaultImage();
			// 如果是完整的HTTP URL，直接返回
			if(path.startsWith('http')) return path;
			// 如果是 base64 格式，直接返回
			if(path.startsWith('data:image')) return path;
			// 如果是相对路径（以/开头），拼接服务器地址
			if(path.startsWith('/')) {
				// 如果已经是 /img/ 开头，直接拼接
				if(path.startsWith('/img/')) {
					return 'http://localhost:8888' + path;
				}
				// 如果是其他路径（如 /2024-10-26/xxx.jpg），需要添加 /img 前缀
				return 'http://localhost:8888/img' + path;
			}
			// 其他情况，添加服务器前缀和路径分隔符
			return 'http://localhost:8888/img/' + path;
		},
		getDefaultImage(){
			// 返回一个包含食物emoji的SVG图片
			const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f5f5f5" rx="10"/><text x="100" y="100" font-size="80" text-anchor="middle" dominant-baseline="central">🥤</text></svg>';
			return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
		},
		handleImageError(event){
			event.target.src = this.getDefaultImage();
		},
		toUserAddress(){
			this.$router.push({path:'/userAddress',query:{
				businessId:this.businessId,
				foodArr:this.$route.query.foodArr
			}});
		},
		loadUserLevelInfo(){
			let user = this.$getSessionStorage('user');
			if (!user || !user.userId) {
				return;
			}
			
			this.$axios.post('UserController/user/info', this.$qs.stringify({
				userId: user.userId
			}), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			})
			.then(resp => {
				if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
					const userInfo = resp.data.result || {};
					this.userLevel = userInfo.level || 1;
					this.userDiscount = userInfo.discount || 99;
				}
			})
			.catch(err => {
				console.error('加载用户等级信息失败:', err);
			});
		},
		loadAvailableCoupons(){
			let user = this.$getSessionStorage('user');
			if (!user || !user.userId) {
				return;
			}
			
			this.$axios.post('UserCouponController/available', this.$qs.stringify({
				userId: user.userId
			}), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			})
			.then(resp => {
				if (resp.data && (resp.data.code === 200 || resp.data.code === '200')) {
					this.availableCoupons = resp.data.result || [];
				}
			})
			.catch(err => {
				console.error('加载优惠券失败:', err);
			});
		},
		toPayment(){
		if(this.deliveryaddress==null || !this.deliveryaddress.daId){
			alert('请选择送货地址！');
			return;
		}
			
			// 使用优惠券创建订单
			const couponId = this.selectedCouponId ? parseInt(this.selectedCouponId) : null;
			const endpoint = couponId ? 'OrdersController/createOrdersWithCoupon' : 'OrdersController/createOrders';
			const params = {
				userId:this.user.userId,
				businessId:this.businessId,
				orderTotal:this.subtotal,
				daId:this.deliveryaddress.daId
			};
			
			if (couponId) {
				params.couponId = couponId;
			}
			
			this.$axios.post(endpoint, this.$qs.stringify(params), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			}).then(response=>{
				console.log(response.data);
				if(response.data.code=='200'){
					let orderId = response.data.result;
					this.$router.push({path:'/payment',query:{orderId:orderId}});
				}else{
					alert('创建订单失败：' + (response.data.message || '未知错误'));
				}
			}).catch(error=>{
				console.error('创建订单错误：', error);
				alert('创建订单失败，请重试！');
			});
		},
			roundToDecimalPlace(num, decimalPlaces) {
				const factor = Math.pow(10, decimalPlaces);
				return Math.round(num * factor) / factor;
			},
		getdeliveryaddress(){
			// 从 localStorage 读取用户选择的地址
			const selectedAddress = this.$getLocalStorage('selectedAddress_' + this.user.userId);
			if (selectedAddress) {
				this.deliveryaddress = selectedAddress;
			}
		}
		},components: {
			BackButton
		}
	}
</script>

<style scoped>
	.wrapper {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 18vw;
	}

	/****************** header部分 ******************/
	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 订单信息卡片 ******************/
	.order-info-card {
		width: 100%;
		margin-top: 0;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
		border-radius: 0 0 20px 20px;
		padding: 4vw;
		box-sizing: border-box;
		box-shadow: 0 4px 12px rgba(0,0,0,0.15);
	}

	.card-header {
		display: flex;
		align-items: center;
		gap: 2vw;
		margin-bottom: 3vw;
	}

	.card-header .material-icons {
		font-size: 5vw;
	}

	.card-header h5 {
		font-size: 3.5vw;
		font-weight: 400;
		margin: 0;
		opacity: 0.9;
	}

	.order-info-address {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: rgba(255,255,255,0.15);
		padding: 3vw;
		border-radius: 12px;
		margin-bottom: 3vw;
		cursor: pointer;
		transition: all 0.3s;
	}

	.order-info-address:active {
		background-color: rgba(255,255,255,0.25);
	}

	.address-text {
		flex: 1;
		font-size: 4.5vw;
		font-weight: 600;
		margin: 0;
	}

	.order-info-address .material-icons {
		font-size: 6vw;
		opacity: 0.8;
	}

	.user-info {
		display: flex;
		align-items: center;
		gap: 2vw;
		font-size: 3.2vw;
		opacity: 0.9;
	}

	.user-info .material-icons {
		font-size: 4vw;
	}

	/****************** 商家信息卡片 ******************/
	.business-card {
		display: flex;
		align-items: center;
		gap: 3vw;
		padding: 4vw;
		background-color: #fff;
		margin: 3vw 0;
		border-radius: 16px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.08);
	}

	.business-icon {
		font-size: 6vw;
		color: #667eea;
	}

	.business-card h3 {
		font-size: 4.5vw;
		font-weight: 600;
		color: #333;
		margin: 0;
	}

	/****************** 订单明细卡片 ******************/
	.order-items-card {
		background-color: #fff;
		border-radius: 16px;
		margin: 3vw;
		box-shadow: 0 2px 12px rgba(0,0,0,0.08);
		overflow: hidden;
	}

	.order-items-card .card-header {
		background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 3vw 4vw;
		margin: 0;
	}

	.order-items-card .card-header .material-icons {
		color: #667eea;
	}

	.order-items-card .card-header h5 {
		color: #333;
		font-weight: 600;
		font-size: 4vw;
	}

	.order-items-list {
		padding: 2vw 0;
	}

	.order-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 3vw 4vw;
		border-bottom: 1px solid #f0f0f0;
	}

	.order-item:last-child {
		border-bottom: none;
	}

	.item-left {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
	}

	.item-img {
		width: 14vw;
		height: 14vw;
		border-radius: 10px;
		object-fit: cover;
		box-shadow: 0 2px 6px rgba(0,0,0,0.1);
	}

	.item-info {
		flex: 1;
	}

	.item-name {
		font-size: 3.8vw;
		font-weight: 500;
		color: #333;
		margin: 0 0 1vw 0;
	}

	.item-quantity {
		font-size: 3.2vw;
		color: #999;
		margin: 0;
	}

	.item-price {
		font-size: 4.2vw;
		font-weight: 600;
		color: #667eea;
		margin: 0;
	}

	.delivery-fee-item {
		background-color: #f8f9fa;
	}

	.delivery-icon {
		font-size: 5vw;
		color: #667eea;
	}

	.delivery-fee-item .item-name {
		margin: 0;
	}

	/****************** 合计部分 ******************/
	.total-bar {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		min-height: 16vw;
		background-color: #fff;
		box-shadow: 0 -2px 12px rgba(0,0,0,0.1);
		display: flex;
		align-items: flex-start;
		padding: 2vw 4vw;
		box-sizing: border-box;
		gap: 2vw;
		z-index: 100;
	}

	.total-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 0.8vw;
		padding-top: 1vw;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 3.2vw;
	}

	.price-row.total {
		border-top: 1px solid #e0e0e0;
		padding-top: 0.8vw;
		margin-top: 0.8vw;
	}

	.price-label {
		color: #666;
	}

	.price-label.discount {
		color: #4CAF50;
	}

	.price-amount {
		font-weight: 600;
		color: #333;
	}

	.price-amount.discount {
		color: #4CAF50;
	}

	.total-label {
		font-size: 3.8vw;
		color: #666;
		font-weight: 600;
	}

	.total-amount {
		font-size: 5.5vw;
		font-weight: 700;
		color: #ff6b6b;
	}

	.discount-icon {
		font-size: 3.5vw;
		vertical-align: middle;
		margin-right: 1vw;
	}

	.savings-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1vw;
		margin-top: 0.5vw;
		padding: 1.2vw 1.5vw;
		background: linear-gradient(135deg, rgba(76, 175, 80, 0.1) 0%, rgba(76, 175, 80, 0.05) 100%);
		border-radius: 6px;
		border: 1px solid rgba(76, 175, 80, 0.2);
	}

	.savings-tip .material-icons {
		font-size: 2.8vw;
		color: #4CAF50;
		flex-shrink: 0;
	}

	.savings-tip span {
		font-size: 2.8vw;
		color: #4CAF50;
		font-weight: 600;
		white-space: nowrap;
	}

	/* 优惠券卡片 */
	.coupon-card {
		background-color: white;
		border-radius: 16px;
		margin: 3vw;
		box-shadow: 0 2px 12px rgba(0,0,0,0.08);
		overflow: hidden;
	}

	.coupon-card .card-header {
		background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 3vw 4vw;
		margin: 0;
	}

	.coupon-card .card-header .material-icons {
		color: #667eea;
	}

	.coupon-card .card-header h5 {
		color: #333;
		font-weight: 600;
		font-size: 4vw;
	}

	.coupon-selector {
		padding: 2vw 0;
	}

	.coupon-select {
		width: 100%;
		padding: 3vw;
		border: 1px solid #ddd;
		border-radius: 8px;
		font-size: 3.5vw;
		color: #333;
		background-color: #fff;
		cursor: pointer;
	}

	.coupon-list {
		display: flex;
		flex-direction: column;
		gap: 0;
		padding: 0;
	}

	.coupon-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 3vw 4vw;
		background-color: #fff;
		border-bottom: 1px solid #f0f0f0;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.coupon-item:last-child {
		border-bottom: none;
	}

	.coupon-item:hover {
		background-color: #f8f9fa;
	}

	.coupon-item.selected {
		background-color: #f0f4ff;
		border-left: 3px solid #667eea;
	}

	.coupon-item-left {
		display: flex;
		align-items: center;
		gap: 3vw;
		flex: 1;
		min-width: 0;
	}

	.coupon-item-left .material-icons {
		font-size: 5vw;
		color: #667eea;
		flex-shrink: 0;
	}

	.coupon-amount {
		display: flex;
		align-items: baseline;
		gap: 0.5vw;
		min-width: 10vw;
		flex-shrink: 0;
	}

	.currency {
		font-size: 2.5vw;
		color: #667eea;
		font-weight: 600;
	}

	.amount {
		font-size: 4vw;
		color: #667eea;
		font-weight: bold;
	}

	.coupon-info {
		flex: 1;
		min-width: 0;
	}

	.coupon-name {
		font-size: 3.8vw;
		font-weight: 500;
		color: #333;
		margin: 0 0 1vw 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.coupon-condition {
		font-size: 3.2vw;
		color: #999;
		margin: 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.check-icon {
		font-size: 5vw;
		color: #ddd;
		transition: all 0.3s ease;
		flex-shrink: 0;
		margin-left: 1vw;
	}

	.coupon-item.selected .check-icon {
		color: #667eea;
	}

	.no-coupon-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 2vw;
		padding: 4vw;
		text-align: center;
		color: #999;
	}

	.no-coupon-tip .material-icons {
		font-size: 6vw;
		color: #ddd;
	}

	.no-coupon-tip span {
		font-size: 3.5vw;
		color: #666;
	}

	.link-to-store {
		display: inline-block;
		margin-top: 2vw;
		padding: 2.5vw 4vw;
		background-color: #1976D2;
		color: white;
		text-decoration: none;
		border-radius: 6px;
		font-size: 3.2vw;
		font-weight: 600;
		transition: all 0.3s ease;
	}

	.link-to-store:hover {
		background-color: #1565C0;
		box-shadow: 0 2px 8px rgba(25, 118, 210, 0.3);
	}

	.pay-button {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
		border: none;
		border-radius: 8px;
		padding: 2.5vw 4vw;
		font-size: 3.5vw;
		font-weight: 600;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1.5vw;
		box-shadow: 0 4px 12px rgba(102,126,234,0.4);
		transition: all 0.3s;
		flex-shrink: 0;
		white-space: nowrap;
	}

	.pay-button:active {
		transform: scale(0.95);
		box-shadow: 0 2px 8px rgba(102,126,234,0.3);
	}

	.pay-button .material-icons {
		font-size: 4vw;
	}
</style>
